<template>
    <div id="new-teacher">
        <el-breadcrumb separator="/" class="common-bread">
            <el-breadcrumb-item :to="{ path: '/teacher' }">教师管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{operationText}}教师</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="form mt10 contentBox">
            <div class="list_head">
                <span class="head_name">教师信息</span>
                <el-button type="primary" @click="$router.push('/teacher')" class="fr ml10">取消</el-button>
                <el-button type="primary" @click="save" class="fr">保存</el-button>
            </div>
            <el-form label-width="120px" :model="form" :rules="rules" ref="form">
                <el-form-item label="学校：" prop="schoolName">
                    <el-autocomplete v-model="form.schoolName" :fetch-suggestions="querySearch" placeholder="请输入使用学校"
                        @select="handleSelect" clearable></el-autocomplete>
                </el-form-item>
                <el-form-item label="教师姓名：" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="性别：" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="手机号：" prop="phone">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="教职工号：" prop="workNumber">
                    <el-input v-model="form.workNumber"></el-input>
                </el-form-item>
                <el-form-item label="管理班级：">
                    <el-form-item ref="grade" prop="gradeId" class="inline">
                        <el-select v-model="form.gradeId" @change="getSavedClass">
                            <el-option :label='item.gradeName' :value='item.gradeId' :key='item.gradeId' v-for="item in grades"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item ref="class" prop="classId" class="inline">
                        <el-select v-model="form.classId">
                            <el-option :label='item.name' :value='item.classId' :key='index' v-for="(item,index) in classes"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-button type="primary" @click="addClass">添加</el-button>
                    <div class="campContain">
                        <span v-for="(item,index) in form.manageClasses" class="campSpan" :key="index">{{item.className}}
                            <i @click="deleteClass(index)" class="el-icon-circle-close"></i>
                        </span>
                    </div>
                </el-form-item>


            </el-form>
        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from "vuex";
    export default {
        data() {
            let validBlank = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    callback();
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            let validCode = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    if (value.length > 50) {
                        callback(new Error("字符长度不能超过50个字符"));
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            let validPhone = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    if (!/^1[3456789]\d{9}$/.test(value)) {
                        callback("请输入格式正确的联系电话");
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            return {
                id: "",
                operationText: "添加",
                schoolId: "",
                areaId: "",
                schools: [],
                grades: this.$util.getGrades(),
                classes: [],
                form: {
                    schoolName: "",
                    name: "",
                    gender: "1",
                    phone: "",
                    workNumber: "",
                    gradeId: '',
                    classId: "",
                    manageClasses: []
                },
                rules: {
                    schoolName: [
                        { required: true, message: "学校名称不能为空", trigger: "change" }
                    ],
                    name: [
                        { required: true, message: "教师姓名不能为空", trigger: "blur" },
                        { validator: validBlank }
                    ],
                    gender: [
                        { required: true }
                    ],
                    phone: [
                        { required: true, message: "手机号不能为空", trigger: "blur" },
                        { validator: validPhone, trigger: "blur" }
                    ],
                    workNumber: [
                        { required: true, message: "教职工号不能为空", trigger: "blur" },
                        { validator: validCode }
                    ]
                }
            }
        },
        computed: mapState({ user: state => state.user }),
        mounted() {
            this.$util.setStore("teacSelect", "1");
            this.id = this.$util.getUrlParam("id");
            this.getSchools().then(schools => {
                if (this.id) {
                    this.operationText = "编辑";
                    this.getDetail();
                } else {
                    this.getSavedClass();
                }
            });
        },
        methods: {
            //获取学校列表
            getSchools() {
                return new Promise(resolve => {
                    this.$util.getSchools().then(schools => {
                        schools.forEach(item => {
                            this.schools.push({
                                value: item.name,
                                schoolId: item.schoolId,
                                areaId: item.areaId,
                                haveHigh: item.haveHigh,
                                haveMiddle: item.haveMiddle,
                                havePrimary: item.havePrimary
                            })
                        });

                        resolve(schools);
                    });
                })
            },
            //根据年级和学校获取已经存在班级
            getSavedClass() {
                this.$axios.get("/adminapi/v1/tools/classes/list", {
                    params: {
                        grade: this.form.gradeId,
                        schoolId: this.schoolId,
                        pageSize: 100,
                        pageNum: 1
                    }
                }).then(response => {
                    if (response.data.error == 10000) {
                        this.classes = [];
                        this.$refs.class.resetField();
                        if (!response.data.data) return;
                        let list = response.data.data.content;
                        list.forEach(item => {
                            let gradeName = this.$util.gradeFormat(item.grade * 1);
                            let className = gradeName + item.number + "班";
                            item.name = item.name ? className + `（${item.name}）` : className;

                            this.classes.push({
                                name: item.name, classId: item.classId
                            })
                        })
                    }
                })
            },
            createFilter(queryString) {
                return (school) => {
                    return (school.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
                };
            },
            querySearch(queryString, cb) {
                let schools = this.schools;
                let results = queryString ? schools.filter(this.createFilter(queryString)) : schools;
                // 调用 callback 返回建议列表的数据
                cb(results);
                results = [];
            },
            handleSelect(item) {
                this.schoolId = item.schoolId;
                this.areaId = item.areaId;
                let schoolType = [];
                if (item.haveHigh) schoolType.push("高中");
                if (item.haveMiddle) schoolType.push("初中");
                if (item.havePrimary) schoolType.push("小学");
                this.$refs.grade.resetField();
                this.$refs.class.resetField();
                this.grades = this.$util.getGrades(schoolType);

                this.getSavedClass();
            },
            save() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        let manageClasses = [];

                        this.form.manageClasses.forEach(item => {
                            manageClasses.push({
                                classId: item.classId,
                                schoolId: item.schoolId
                            })
                        })

                        let requestParam = {
                            name: this.form.name.trim(),
                            schoolId: this.schoolId,
                            gender: this.form.gender * 1,
                            phone: this.form.phone.trim(),
                            areaId: this.areaId,
                            workNumber: this.form.workNumber.trim(),
                            teacherClassModelList: manageClasses
                        }

                        if (this.id) requestParam.teacherId = this.id;
                        this.$axios.post("/adminapi/v1/tools/teachers/addOrEdit", requestParam).then(response => {
                            if (response.data.error == 10000) {
                                this.$router.push("/teacher");
                                this.$util.successMsg("保存成功");
                            } else {
                                this.$util.errorMsg(response.data.message);
                            }
                        })
                    }
                })
            },
            //获取教师详情
            getDetail() {
                this.$axios.get("/adminapi/v1/tools/teachers/info?teacherId=" + this.id).then(response => {
                    if (response.data.error == 10000) {
                        let info = response.data.data;
                        this.schoolId = info.schoolId;
                        this.areaId = info.areaId;
                        let manageClasses = [];
                        if (info.teacherClassModelList && info.teacherClassModelList.length) {
                            info.teacherClassModelList.forEach(item => {
                                let gradeName = this.$util.gradeFormat(item.grade * 1);
                                let className = gradeName + item.number + "班";
                                item.className = item.className ? className + `（${item.className}）` : className;
                                manageClasses.push({
                                    className: item.className,
                                    classId: item.classId,
                                    schoolId: item.schoolId
                                });
                            });
                        }

                        this.schools.forEach(item => {
                            if (item.schoolId == info.schoolId) {
                                let schoolType = [];
                                if (item.haveHigh) schoolType.push("高中");
                                if (item.haveMiddle) schoolType.push("初中");
                                if (item.havePrimary) schoolType.push("小学");
                                this.grades = this.$util.getGrades(schoolType);
                            }
                        })

                        this.form = {
                            name: info.name,
                            schoolName: info.schoolName,
                            gender: info.gender + "",
                            phone: info.phone + "",
                            workNumber: info.workNumber + "",
                            classId: "",
                            gradeId: "",
                            manageClasses: manageClasses
                        };

                        this.getSavedClass();
                    }
                })
            },
            addClass() {
                if (!this.form.classId || !this.form.gradeId) return;
                let classObj = this.classes.find((item => {
                    return item.classId == this.form.classId;
                }))

                let item = {
                    className: classObj.name,
                    classId: this.form.classId,
                    schoolId: this.schoolId
                };

                let flag = true;
                this.form.manageClasses.forEach(i => {
                    if (i.classId == item.classId) return flag = false;
                })
                this.$refs.grade.resetField();
                this.$refs.class.resetField();
                if (flag) this.form.manageClasses.push(item);
            },
            deleteClass(index) {
                this.form.manageClasses.splice(index, 1);
            },
            changeGrade() {
                this.getSavedClass();
            }
        }
    }
</script>
<style>
    #new-teacher .el-autocomplete>.el-input {
        width: 300px;
    }

    .campContain {
        width: 700px;
        height: 135px;
        margin-top: 20px;
        border: solid 1px gray;
        box-sizing: border-box;
        overflow-y: scroll;
    }

    #new-teacher .campSpan {
        display: block;
        text-align: center;
        float: left;
        padding: 0 30px 0px 15px;
        border: solid 1px #999;
        border-radius: 5px;
        margin: 10px;
        box-sizing: border-box;
        font-size: 12px;
        position: relative;
        cursor: pointer;
    }

    #new-teacher .campSpan i {
        width: 20px;
        height: 20px;
        line-height: 20px;
        color: #999;
        position: absolute;
        right: 5px;
        top: 11px;
    }

    #new-teacher .inline {
        display: inline-block;
    }
</style>